<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index page</title>
    <script>
        function del() {
            return confirm("delete this record ?")
        }
    </script>
    <script src="/js/axios.min.js"></script>
</head>
<body>
<h1 th:text="'hello, Thymeleaf'">hello,html</h1>
<form id="create">
    <input id="username" type="text" name="username" placeholder="Username" required><br>
    <input id="password" type="password" name="password" placeholder="Password" required><br>
    <input type="checkbox" name="hobbies" value="Movie">Movie
    <input type="checkbox" name="hobbies" value="Game">Game
    <input type="checkbox" name="hobbies" value="Basketball">Basketball
    <input type="checkbox" name="hobbies" value="Football">Football
    <br>

        <select name="cities" multiple>
            <option value="Tianjin"> Tianjin
            <option value="Beijing"> Beijing
            <option value="Shanghai"> Shanghai
            <option value="Shanxi"> Shanxi
        </select>
        <br>
    <input type="submit" value="Go">
</form>
<hr>
<table id="users_table" th:fragment="user_list" border="1">
    <tr>
        <th>id</th>
        <th>username</th>
        <th>password</th>
        <th>hobbies</th>
        <th colspan="3">operations</th>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}">1</td>
        <td th:text="${user.username}">Tom</td>
        <td th:text="${user.password}">123</td>
        <td th:text="${user.hobbies}">123</td>
        <td><a th:href="@{/user/queryById/{id}(id=${user.id})}">edit</a></td>
        <td><a th:href="@{'/user/removeById/' + ${user.id}}" onclick="return del()">remove</a></td>
    </tr>
</table>
<script>
    const form = document.getElementById('create');

    form.addEventListener('submit', function (event) {
        event.preventDefault();
        //阻止表单提交

        let formData = new FormData(form);
        let data = Object.fromEntries(formData);
        let hobbies = formData.getAll('hobbies');
        let cities = formData.getAll('cities');
        data = {...data, hobbies: JSON.stringify(hobbies)}
        // JSON.stringify() : 把JS （数组，对象）转换为 json 字符串
        // console.log(data);

        axios.post('/user/create', data).then(res => {
            console.log(res.data);
            document.getElementById('users_table').innerHTML = res.data;
        //     局部刷新
        }).catch(err => {
            console.log(err);
        })
    });
    //         添加事件监听器 当提交时
</script>
</body>
</html>